

package org.apache.ocean.udp;

import java.net.*;
import org.apache.ocean.URLParameters;


/**
 *
 * @author jasonr
 */
public class UDPUtil {
  
  
  public UDPUtil() {
  }
  
  public static void send(String host, int port, String data, DatagramSocket socket) throws Exception {
    InetAddress inetAddress = InetAddress.getByName(host);
    DatagramPacket packet = UDPUtil.toPacket(inetAddress, port, data);
    socket.send(packet);
  }
  
  public static DatagramPacket toPacket(InetAddress inetAddress, int port, URLParameters parameters) throws Exception {
    String encoded = parameters.toURLEncoded();
    return toPacket(inetAddress, port, encoded);
  }
  
  public static DatagramPacket toPacket(InetAddress inetAddress, int port, String data) throws Exception {
    byte[] bytes = data.getBytes("UTF-8");
    DatagramPacket packet = new DatagramPacket(bytes, bytes.length, inetAddress, port);
    return packet;
  }
  
  public static DatagramPacket toPacket(String data) throws Exception {
    byte[] bytes = data.getBytes("UTF-8");
    DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
    return packet;
  }
  
  public static URLParameters toURLParameters(DatagramPacket packet) throws Exception {
    URLParameters parameters = new URLParameters(toString(packet));
    return parameters;
  }
  
  public static String toString(DatagramPacket packet) {
    String str = new String(packet.getData(), packet.getOffset(), packet.getLength());
    return str;
  }
}
